const socketWrapper = require('./index');
const { redisGet } = require('../utils/redis')
const { getChatHistory, getServiceChatHistoryMsg } = require('../model/msg')

// 等待 Socket.IO 初始化完成后再使用
function setChatHistory() {
    try {
        const io = socketWrapper.getIO();
        io.on('connection', async (socket) => {
            socket.on('chatHistory', async (data, callback) => {
                let { imKey, page, pageSize } = data;
                if (!imKey) {
                    callback({
                        code: 500,
                        message: 'imKey not found'
                    });
                    return;
                }
                if (!page) page = 1;
                if (!pageSize) pageSize = 10;
                const fromUserInfo = await redisGet(`mim-${imKey}`)
                console.log('fromUserInfo', fromUserInfo)
                if (fromUserInfo && fromUserInfo.userType === 3) { // 如果是获取客服消息历史记录，使用不同得方法
                    console.log(3)
                    const list = await getServiceChatHistoryMsg(socket.imKey, { page, pageSize })
                    console.log('getServiceChatHistoryMsg list', list)
                    callback({
                        code: 200,
                        data: [...list.list],
                        total: list.total
                    });
                } else {
                    const list = await getChatHistory(imKey, socket.imKey, page, pageSize);
                    console.log(list.list.length, list.total)
                    callback({
                        code: 200,
                        data: [...list.list],
                        total: list.total
                    });
                }
            });
        });
    } catch (error) {
        console.error('Socket.IO 未初始化:', error);
        callback({
            code: 500,
            message: error.message
        });
    }
}

module.exports = setChatHistory;
